﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace SimpleORM
{
    public class JoinTranslator : LambdaTranslator
    {
        #region Properties

        //public Expression SelectExpression { get; private set; }

        #endregion

        #region Ctor

        public JoinTranslator()
        {
        }

        #endregion

        #region Methods

        #region Methods - Public

        public override void Translate(Expression expression)
        {
            MethodCallExpression m = expression as MethodCallExpression;

            ConstantExpression c = m.Arguments[1] as ConstantExpression;
            if (c != null)
            {
                Type type = (c.Value as IQueryContext).ElementType;
                ObjectContext oc = ObjectContextDictionary.Get(type);

                Stack.Push(DataSource.CreateScriptFactory().
                      SchemaObject(oc.Schema, oc.TableName).
                      As(DataSource.CreateScriptFactory().
                      Constant(FromNameDictionary.Set(type)).
                      Stress()));
            }
            else
            {
                ExpressionTranslater t = DataSource.CreateExpressionTranslater();
                t.Translate(m.Arguments[1]);

                ObjectContextDictionary.Set(t.ResultObjectContext);

                Stack.Push(t.Result.
                      Bracket().
                      As(DataSource.CreateScriptFactory().
                      Constant(FromNameDictionary.Set(t.ResultObjectContext.ElementType)).
                      Stress()));
            }

            this.Visit(Evaluator.PartialEval(m.Arguments[2]));
            this.Visit(Evaluator.PartialEval(m.Arguments[3]));

            List<IScriptFactory> list = Stack.ToList();
            list.Reverse();

            IScriptFactory target = list[0];
            IScriptFactory left = list[1];
            IScriptFactory right = list[2];

            Result = DataSource.CreateScriptFactory().Join(target, left.Equal(right));

            //SelectExpression = ((m.Arguments[4] as UnaryExpression).Operand as LambdaExpression).Body;
            //SelectTranslator = new SelectTranslator();
            //SelectTranslator.Factory = Factory;
            //SelectTranslator.ObjectContextDictionary = ObjectContextDictionary;
            //SelectTranslator.FromNameDictionary = FromNameDictionary;
            //SelectTranslator.Translate((expression.Arguments[4] as UnaryExpression).Operand as LambdaExpression);
        }

        #endregion

        #region Methods - Visit

        #endregion

        #endregion
    }
}
